from api import api

from store import store as storeBase


class PageModelBase(object):
    _instances = {}

    def __new__(cls, name, store):
        ins = cls._instances.get(name)
        if ins:
            return ins

        ins = object.__new__(cls)
        cls._instances[name] = ins
        ins._name = name
        ins.store = store
        # ins.Model = api.env[Model._name]

        # print('page,', name, store)

        return ins

    def __getattr__(self, index):
        # print('in page', index)
        # print('in page, self.store',  self.store)
        # print('in page, self.store[index]', self.store[index])

        return self.store[index]

    def __getitem__(self, index):
        return self.store[index]


class PageMixin(PageModelBase):

    def handleSearch(self, domain):
        self.store.search(domain)

    def handleBrowse(self, rid):
        self.store.browse_one(rid)

    def handleNew(self, context=None):
        self.store.default_get_onchange(context=context)

    def handleOnchange(self, field, value, context=None):
        self.store.onchange(field, value, context=context)

    def submitCreate(self):
        self.store.submitCreate()

    def submitWrite(self, rid):
        self.store.submitWrite(rid)

    def handelDel(self, rid):
        self.store.unlink(rid)

    def handleEdit(self, rid):
        self.store.browse_one(rid, isEdit=1)


class PageModel(PageMixin):
    def showList(self, domain):
        self.handleSearch(domain)

    def showView(self, rid):
        self.handleBrowse(rid)

    def showForm(self, rid=None):
        self.store.fields_get()
        if rid:
            self.handleEdit(rid)
        else:
            self.handleNew()

    def InitO2mForm(self, field):
        self.store.set_o2mForm(field)

    def showO2mForm(self, o2m_field, o2m_id=None):
        if o2m_id:
            self.store.o2m_edit(o2m_field, o2m_id)
        else:
            self.store.o2m_default_get_onchange(o2m_field)


class Page(object):
    def __init__(self):
        self._stores = {}
        for addon in api.addons:
            print('in view,', addon)
            name = ''.join([wd.capitalize() for wd in addon._name.split('.')])
            name = name[0].lower() + name[1:]
            self._stores[name] = storeBase[name]

    def __getitem__(self, index):
        if self._stores.get(index):
            return PageModel(index, self._stores.get(index))
        else:
            raise NameError
            # return None

    def __getattr__(self, index):
        if self._stores.get(index):
            return PageModel(index, self._stores.get(index))
        else:
            raise NameError
            # return None


page = Page()
